package cn.itcast.web.controller.company;

import cn.itcast.domain.company.Company;
import cn.itcast.service.company.CompanyService;
import cn.itcast.web.controller.system.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 企业控制器
 */

@Controller
@RequestMapping("/company")
public class CompanyController extends BaseController {

  //注入企业service对象
  @Reference
  private CompanyService companyService;

  /*
   * 查询所有企业
   */
  @RequestMapping("/list")
  @RequiresPermissions("企业管理")
  public String list(@RequestParam(defaultValue = "1") int pageNum,@RequestParam(defaultValue = "5") int pageSize, HttpServletRequest request) {
    //使用硬编码方式实现权限检查
    Subject subject = SecurityUtils.getSubject();
    subject.checkPermission("企业管理");
    PageInfo<Company> pageInfo = companyService.findByPage(pageNum, pageSize);
    request.setAttribute("pageInfo", pageInfo);
    return "company/company-list";
  }

  /*
   * 添加企业
   */
  @RequestMapping("/save")
  public String save(Date date) {
    System.out.println(date);
    return "success";
  }

  /*
   * 进入新增页面company/company-add.jsp
   */
  @RequestMapping("/toAdd")
  public String toAdd() {
    return "company/company-add";
  }

  /*
   * 企业数据保存
   * 请求地址：/company/edit.do
   * 响应地址：重定向到列表页面
   */
  @RequestMapping("/edit")
  public String edit(Company company) {
    if (StringUtil.isEmpty(company.getId())) {
      //添加
      companyService.save(company);
    } else {
      //修改
      companyService.update(company);
    }
    return "redirect:/company/list.do";
  }

  /*
   * 进入修改页面
   * 请求地址：/company/toUpdate.do?id=1
   * 响应地址：/company/company_update.jsp
   */
  @RequestMapping("/toUpdate")
  public String toUpdate(String id, HttpServletRequest request) {
    //调用方法根据Id查找到对应的企业信息
    Company company = companyService.findById(id);
    //把对应的企业存入到会话域中用于回显
    request.setAttribute("company", company);
    return "company/company-update";
  }

  @RequestMapping("/delete")
  public String delete(String id) {
    companyService.deleteById(id);
    return "redirect:/company/list.do";
  }
}
